<script lang="ts">
export default {
  name: 'Study5StuDemo5'
}
</script>

<template>
  <h2>侦听器-副作用清理</h2>
  <div class="note">
    <h3>onCleanup</h3>
    <p>1. 注册清理逻辑：通过 onCleanup 注册一个清理函数，这个函数会在组件卸载时执行，清理定时器。</p>
  </div>

  <hr class="hr-style" />
  <div class="test">
    <div>
      <input :disabled="isDisabled" v-model="wenti" type="text" placeholder="请输入问题" />
      <p>问题的结果：{{ daan }}</p>
      <p style="padding: 10px; font-size: 33px">{{ num }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

import { debounce } from 'lodash'

// 问题
const wenti = ref('')
// 问题的答案
const daan = ref('')
// 是否禁用
const isDisabled = ref(false)

const num = ref(0)

watch(
  wenti,
  debounce((newVal, oldVal, onCleanup) => {
    const timeoutid = setInterval(() => {
      num.value++
    }, 1000)
    console.log('监听器被执行')

    onCleanup(() => {
      console.log('触发onCleanup')

      clearInterval(timeoutid)
    })
  }, 500)
)
</script>

<style scoped>
body {
  padding: 20px;
}
h2 {
  color: red;
}
h3 {
  color: rgb(220, 85, 85);
}
h4 {
  color: skyblue;
}
.hr-style {
  border: 3px solid gold;
  margin: 20px 0;
}
.note {
  margin: 10px;
  padding: 10px;
  border: 3px solid rgb(221, 121, 202);
}
.note p {
  color: rgb(226, 106, 204);
  font-weight: bold;
}
</style>
